import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { serialize } from '@/utils/util'
import store from '@/store'
import router from '@/router/'
import { getToken } from '@/utils/auth'
import website from '@/config/website'

console.log("-------utils---下面的---store------------")
console.log(store)


// create an axios instance
const service = axios.create({
  //baseURL: '/', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
  validateStatus:function(status){
    return status >= 200 && status <=500; 
  }
})


//Http Request 拦截
service.interceptors.request.use( config => {

  const meta = (config.meta || {});
  const isToken = meta.isToken === false;

  if( getToken() && !isToken ) {
    config.headers['Authorization'] = 'Bearer ' + getToken();
  }

  if(config.method === 'post' && meta.isSerialize === true) {
    Object.keys(config.data).forEach(ele => {
      if(typeof config.data[ele] === 'undefined'){
        delete config.data[ele];
      }
    })

    config.data = serialize(config.data);
  };

  return config;

}, error => {
  return Promise.reject(error)
})



// response interceptor
service.interceptors.response.use(res => {
  const status = Number(res.status) || 200;
  //白名单status
  const statusWhiteList = website.statusWhiteList || [];
  if(statusWhiteList.includes(status)) return Promise.reject(res);



  const message = res.data.message || '未知错误';

  //401 跳转到登陆页面
  if( status === 401 ) store.dispatch('user/FedLogOut').then(() => router.push({path: '/login' }));
  
  //请求为非200默认统一处理
  if( status !== 200 ){

    Message({
      message:message,
      type: 'error'
    })
    
    return Promise.reject(new Error(message))
  }  

  return res;  

},
  error => {
    
    return Promise.reject(new Error(error));
  }
)




export default service
